require "global"

require "statPotocol"

require "purchase/pchCenter"

require "res/commonStrDef"
require "gameData"
require "userData"
require "guide"

require "WarningPanel.lua"

require "StartScene"
require "GameScene"
require "LevelScene"


gameUtil = gameUtil or {}

gameUtil.curLuaScene = nil
gameUtil.recordFile = nil

--origin file is "recordfile.lua" , another file is "recordfile2.lua"

local fileUtils = cc.FileUtils:getInstance()
local recordpath = fileUtils:getWritablePath()
print("recordpath = "..recordpath)

if DEF_RECORD_IN_SDCARD then
    if cc.PLATFORM_OS_ANDROID == g_targetPlatform then
        recordpath = "/mnt/sdcard/"
    end
end

local recordfiles = {recordpath.."recordfile.lua", recordpath.."recordfile2.lua"}

function gameUtil.initDataAndSettings()
    gameData:initForApp()

    gameUtil.readSoundSettings()
end

function gameUtil.resetGlobalVars()
    uiPopNotify:reset()
    uiIndicator:reset()
    uiIndicator2:reset()
end

function gameUtil.changeScene(name)
    if gameUtil.curLuaScene then
        gameUtil.curLuaScene:destroy()
    end
    
    gameUtil.resetGlobalVars()

    local cocosScene, scene
    if(name == "start") then
        scene = StartScene.create()
        gameUtil.curLuaScene = scene
        cocosScene = scene.view
    elseif(name == "level") then
        scene = LevelScene.create()
        gameUtil.curLuaScene = scene
        cocosScene = scene.view
    elseif(name == "game") then
        scene = GameScene.create()
        gameUtil.curLuaScene = scene
        scene:readLevel(gameData.level)
        -- scene:prepareBullet_once()
        cocosScene = scene.view
    else
    end

    -- if gameUtil.isMusicFlagOn() then
    --     gameUtil.musicOn()
    -- else
    --     gameUtil.musicOff()
    -- end
    -- if gameUtil.isSoundFlagOn() then
    --     gameUtil.soundOn()
    -- else
    --     gameUtil.soundOff()
    -- end

    if cc.Director:getInstance():getRunningScene() then
        cc.Director:getInstance():replaceScene(cc.TransitionFade:create(0.3,cocosScene))
    else
        cc.Director:getInstance():runWithScene(cocosScene)
    end
end

function gameUtil.readUserRecord()

    local content
    local userRecord

    --return value: 1. success ,  2. none ,   3.broken

    local readret1 = zLua_decrypt_file(recordfiles[1])
    local readret2 = zLua_decrypt_file(recordfiles[2])

    local rcd1,rcd2

    if readret1 == 3 then

        if readret2 == 3 then
            --create new record
        elseif readret2 == 1 then

            gameUtil.recordIdx = 2
            userRecord = dofile(recordfiles[2])
            
        else
            --create new record
        end

    elseif readret1 == 1 then

        if readret2 == 1 then
            --compare modified time to determine loading which
            rcd1 = dofile(recordfiles[1])
            rcd2 = dofile(recordfiles[2])

            if not rcd1.noread_fileLastModifiedSec then --兼容老版
                gameUtil.recordIdx = 1
                userRecord = rcd1
            else
                if rcd1.noread_fileLastModifiedSec > rcd2.noread_fileLastModifiedSec then
                    gameUtil.recordIdx = 1
                    userRecord = rcd1
                else
                    gameUtil.recordIdx = 2
                    userRecord = rcd2
                end
            end
            
        else
            gameUtil.recordIdx = 1
            userRecord = dofile(recordfiles[1])
        end

    else --2

        if readret2 == 1 then
            gameUtil.recordIdx = 2
            userRecord = dofile(recordfiles[2])
        elseif readret2 == 2 then
            --create new rcd
        else --3
            --create new rcd
        end

    end

    if readret1 == 1 then zLua_encrypt_file(recordfiles[1]) end
    if readret2 == 1 then zLua_encrypt_file(recordfiles[2]) end
        

    if userRecord and not IS_RESET_RECORD then
        if type(userRecord) == "table" then
            userData:loadFrom(userRecord)
        end
    else
        userData:initByDefaultData()
    end


    
    ------------------------------------------------------------------
    --android cannot read file modified time by system function

    -- local readret = zLua_decrypt_file(recordfilefullname) 

    -- if readret == 3 then

    --     --get another recordfile
    --     for k,v in pairs(recordfiles) do
    --         if recordfilefullname ~= v then
    --             recordfilefullname = v
    --             break
    --         end
    --     end

    --     readret = zLua_decrypt_file(recordfilefullname)
    --     if readret == 3 then
    --         cc.Director:getInstance():endToLua()
    --     end
    -- end

    -- if readret == 1 and not IS_RESET_RECORD then

    --     -- 
    --     userRecord = dofile(filename)
    --     if type(userRecord) == "table" then
    --         userData:loadFrom(userRecord)
    --     end
    --     zLua_encrypt_file(recordfilefullname)   --恢复加密状态

    -- else --2
    --     userData:initByDefaultData()
    -- end

    ----------------------------------------------------------------------------------
    --only one file stratage:
--     local bExist = zLua_decrypt_file(recordfilefullname)    --解密用户信息

--     if bExist and not IS_RESET_RECORD then

-- --lkj knowledge: 返回local的话，这个loaded table里面应该是匿名table，无法从name找到，返回全局的变量，才能找到
-- --        local nakedfilename = string.gsub(filename, ".lua", "")
-- --        if package.loaded[nakedfilename] then
-- --            package.loaded[nakedfilename] = false
-- --        end

-- --lkj knwledge: require只能读1次，改成dofile可以反复读
--         userRecord = dofile(filename)
--         if type(userRecord) == "table" then
--             userData:loadFrom(userRecord)
--         end
--         zLua_encrypt_file(recordfilefullname)   --恢复加密状态
--     else
--         userData:initByDefaultData()
--     end


    --lua io API
    --end

       -- gameUtil.recordFile = io.open(recordfilefullname, "r")
       -- if not gameUtil.recordFile then
       --     gameUtil.recordFile = io.open(recordfilefullname, "w")
       --     gameUtil.recordFile:close()
       -- else
       --     local file = gameUtil.recordFile
       --     --        content = file:read("*all")
       --     --        userRecord = loadstring(content)
       --     file:close()
       --     userRecord = require("recordfile.lua")
       --     --print_r(userRecord)

       --     if type(userRecord) == "table" then
       --         userData:loadFrom(userRecord)
       --     end

    -- end


end

function gameUtil.flushUserRecord()
    --swap record
    if gameUtil.recordIdx == 1 then
        gameUtil.recordIdx = 2
    else
        gameUtil.recordIdx = 1
    end

    recordfilefullname = recordfiles[gameUtil.recordIdx]

    local userDataStr = userData:toString()

    -- local file = gameUtil.recordFile
    -- file = io.open(recordfilefullname, "w")
    -- file:write(userDataStr)
    -- file:close()

    zLua_flush_string_to_file(recordfilefullname, userDataStr)

    d_print(userDataStr)
end

function gameUtil.unlockNextLevel()
    userData:unlockNextLevel()
end

function gameUtil.handleProcess_gameWin()
    if userData.lives < userData.fulllives then
        userData.lives = userData.lives + 1
    end

    userData:synLevelScoreAndStar()

    gameData:genAward()
    userData.coin = userData.coin + gameData.award.coin
    userData.weaponCnt_fenji = userData.weaponCnt_fenji + gameData.award.fenji
    userData.weaponCnt_yuheng = userData.weaponCnt_yuheng + gameData.award.yuheng

    --------------------
    gameUtil.unlockNextLevel()

    local showlevelcnt = #userData.passedlevelinfo
    if showlevelcnt > levelCfg.lockInterval and showlevelcnt%levelCfg.lockInterval == 1 then
        userData.lockUnlocked = false
    end

    gameUtil.flushUserRecord()
end

function gameUtil.handleProcess_gameFail()
    gameUtil.flushUserRecord()
end

function gameUtil.unlockTheLock()
    userData.lockUnlocked = true
    gameUtil.flushUserRecord()
end


function gameUtil.onClickPlayNextLevel()
    local targetlevel = gameData.level + 1
    local showlevelcnt = #userData.passedlevelinfo
    if targetlevel ==  showlevelcnt and showlevelcnt > levelCfg.lockInterval and showlevelcnt%levelCfg.lockInterval == 1 and userData.lockUnlocked == false then
        gameData.level_needPopLevelInfoPanel = false
    else
        gameData.level_needPopLevelInfoPanel = true
        gameData.level = gameData.level + 1

        --lkj temp:
        if gameData.level >= 80 then
            gameData.level = 80
        end
    end
    gameUtil.changeScene("level")
end

function gameUtil.onClickQianghuaInGameScene()
    gameData.level_needPopIntensifyPanel = true
    gameUtil.changeScene("level")
end

function gameUtil.onClickPlayAgainThisLevel()
    gameData.level_needPopLevelInfoPanel = true
    gameUtil.changeScene("level")
end

--------------------------------------------
function gameUtil.checkLoginAwardStatus()
    return userData:checkGettingLoginAward()
end

function gameUtil.gettingAward(award)
    local strCoin,strFenji,strYuheng = "","",""
    for k,v in pairs(award)do
        if v.gameObjRef == pp.gameObjs.coin then
            userData.coin = userData.coin + v.cnt
            strCoin = string.format("金币%d枚 ", v.cnt)
        elseif v.gameObjRef == pp.gameObjs.yuheng then
            userData.weaponCnt_yuheng = userData.weaponCnt_yuheng + v.cnt
            strYuheng = string.format("玉衡%d个 ", v.cnt)
        elseif v.gameObjRef == pp.gameObjs.fenji then
            userData.weaponCnt_fenji = userData.weaponCnt_fenji + v.cnt
            strFenji = string.format("焚寂%d个 ", v.cnt)
        end
    end

    gameUtil.flushUserRecord()

    local notifystr = "获得:"..strCoin..strFenji..strYuheng
    uiPopNotify:popString(gameUtil.curLuaScene.widget, notifystr)
end

function gameUtil.gettingLoginAward(award)
    local tm = os.date("*t")
    local sec = os.time(tm)
    userData.lastGotLoginAwardSec = sec

    gameUtil.gettingAward(award)
end

--------------------------------------------
--pay
function gameUtil.buyCoin(amount)
    userData.coin = userData.coin + amount
    gameUtil.flushUserRecord()
end

--------------------------------------------
function gameUtil.readSoundSettings()
    if userData.musicOn then
        AudioEngine.setMusicVolume(1)
    else
        AudioEngine.setMusicVolume(0)
    end
    if userData.effectOn then
        AudioEngine.setEffectsVolume(1)
    else
        AudioEngine.setEffectsVolume(0)
    end
end

function gameUtil.musicOff()
    -- AudioEngine.pauseMusic()
    -- gameUtil.isMusicOn = false
    AudioEngine.setMusicVolume(0)
    userData.musicOn = false
    gameUtil.flushUserRecord()
end

function gameUtil.musicOn()
    -- AudioEngine.resumeMusic()
    -- gameUtil.isMusicOn = true
    AudioEngine.setMusicVolume(1)
    userData.musicOn = true
    gameUtil.flushUserRecord()
end

function gameUtil.soundOff()
    AudioEngine.setEffectsVolume(0)
    -- gameUtil.isSoundOn = false
    userData.effectOn = false
    gameUtil.flushUserRecord()
end

function gameUtil.soundOn()
    AudioEngine.setEffectsVolume(1)
    -- gameUtil.isSoundOn = true
    userData.effectOn = true
    gameUtil.flushUserRecord()
end

function gameUtil.playMusic(name, bLoop)
    AudioEngine.playMusic(name, bLoop)
    -- if gameUtil.isMusicOn == false then
    --     AudioEngine.pauseMusic()
    -- end 
end

function gameUtil.playEffect(name)
    AudioEngine.playEffect(name)
end



------------------------------------------------

function gameUtil.sendGameStat(eventtype, var1, var2, var3)
    local stat = {}

    stat.appid = appInfo.appid
    stat.playerid = userData.id

    local tm = os.date("*t")
    stat.time = os.time(tm)

    stat.et = eventtype or -1
    stat.v1 = var1 or 0
    stat.v2 = var2 or 0
    stat.v3 = var3 or 0

    local str = serialize(stat)
    zLua_sendGameStat(str)
end


------------------------------------------------

return gameUtil








